package cn.yunyichina.provider.clinic.listener;

import cn.yunyichina.provider.clinic.dao.FuyinApplyDao;
import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.iface.entity.base.OrderExtVo;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.utils.convert.JsonUtils;
import cn.yunyichina.utils.convert.XmlUtils;

import com.alibaba.fastjson.JSONObject;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.listener.MessageListener;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

public class FuyinPayMessageListener implements MessageListener<Integer, String> {

    private Logger logger = LoggerFactory.getLogger(FuyinPayMessageListener.class);

    @Autowired
    private FuyinApplyDao fuyinApplyDao;

    private final static String TRADE_IS_SUCCESS = "SUCCESS";

    private final static String TRADE_TYPE_APP = "APP";

    public void onMessage(ConsumerRecord<Integer, String> integerStringConsumerRecord) {
//        String xmlString = "<xml><appid>wx2421b1c4370ec43b</appid><attach>支付测试</attach><bank_type>CFT</bank_type><fee_type>CNY</fee_type><is_subscribe>Y</is_subscribe><mch_id>10000100</mch_id><nonce_str>5d2b6c2a8db53831f7eda20af46e531c</nonce_str><openid>oUpF8uMEb4qRXf22hE3X68TekukE</openid><out_trade_no>1409811653</out_trade_no><result_code>SUCCESS</result_code><return_code>SUCCESS</return_code><sign>B552ED6B279343CB493C5DD0D78AB241</sign><sub_mch_id>10000100</sub_mch_id><time_end>20140903131540</time_end><total_fee>1</total_fee><trade_type>JSAPI</trade_type><transaction_id>1004400740201409030005092168</transaction_id></xml>";
        String xmlString = integerStringConsumerRecord.value();
        logger.info("FuyinPayMessageListener.onMessage.xmlString -> {}", xmlString);

        try {
            Map<String, String> doc = XmlUtils.xmlToMap(xmlString);
            Map<String, Object> paramMap = new HashMap<>();
            if (TRADE_TYPE_APP.equalsIgnoreCase(doc.get("trade_type"))) {
                if (TRADE_IS_SUCCESS.equalsIgnoreCase(doc.get("return_code"))) {
                    if (TRADE_IS_SUCCESS.equalsIgnoreCase(doc.get("result_code"))) {
                        logger.info("onMessage, 支付成功，start");
                        try {
                            paramMap.put("payStatus", "1");
                            paramMap.put("payContent", "支付成功，更新订单状态成功");
                            paramMap.put("orderNo", doc.get("out_trade_no"));
                            paramMap.put("agtOrderNum", doc.get("transaction_id"));
                            logger.info("onMessage, paramMap=" + JSONObject.toJSONString(paramMap));
                            fuyinApplyDao.updateByOrderNo(paramMap);
                            logger.info("onMessage, 支付成功，更新订单状态成功。");
                        } catch (Exception ex) {
                            paramMap.put("payStatus", "3");
                            paramMap.put("payContent", "支付成功，更新订单状态失败");
                            paramMap.put("orderNo", doc.get("out_trade_no"));
                            paramMap.put("agtOrderNum", doc.get("transaction_id"));
                            logger.info("onMessage, paramMap=" + JSONObject.toJSONString(paramMap));
                            fuyinApplyDao.updateByOrderNo(paramMap);
                            logger.error("onMessage, 支付成功，更新订单状态失败。", ex);
                        }
                    } else {
                        paramMap.put("payStatus", "2");
                        paramMap.put("payContent", "支付失败，result_code is FAIL");
                        paramMap.put("orderNo", doc.get("out_trade_no"));
                        paramMap.put("agtOrderNum", doc.get("transaction_id"));
                        logger.info("onMessage, paramMap=" + JSONObject.toJSONString(paramMap));
                        fuyinApplyDao.updateByOrderNo(paramMap);
                        logger.info("onMessage, result_code is FAIL. 支付失败。");
                    }
                } else {
                    paramMap.put("payStatus", "4");
                    paramMap.put("payContent", "支付异常，return_code is FAIL");
                    paramMap.put("orderNo", doc.get("out_trade_no"));
                    logger.info("onMessage, paramMap=" + JSONObject.toJSONString(paramMap));
                    fuyinApplyDao.updateByOrderNo(paramMap);
                    logger.info("onMessage, return_code is FAIL. 支付失败。");
                }
            } else {
                paramMap.put("payContent", "支付类型trade_type不是APP，暂时不支持除APP类型外其他支付。");
                paramMap.put("orderNo", doc.get("out_trade_no"));
                logger.info("onMessage, paramMap=" + JSONObject.toJSONString(paramMap));
                fuyinApplyDao.updateByOrderNo(paramMap);
                logger.info("onMessage, 支付类型trade_type不是APP，暂时不支持除APP类型外其他支付。");
            }
            
            String orderNo = doc.get("out_trade_no");
            String openId = doc.get("openid");
            String appId = doc.get("appid");
            String transactionId = doc.get("transaction_id");
            String attach = doc.get("attach");

            Map<String, String> map = new HashMap<String, String>();
            map.put("order_no", orderNo);
            logger.info("病案复印微信支付回调, 订单号" + orderNo + ", 调base模块, 查询订单信息入参request=" + JSONObject.toJSONString(map));
            Response ordResponse = BaseService.callUnderlineFromInternal("yyt.base.order.by.order.no.out.get",
                    JsonUtils.toJsonString(map));
            logger.info(
                    "病案复印微信支付回调, 订单号" + orderNo + ", 调base模块, 查询订单信息返回response=" + JSONObject.toJSONString(ordResponse));
            if (!"0".equals(ordResponse.getResultCode())) {
                logger.info("病案复印微信支付回调, 订单号" + orderNo + ", 调base模块, 查询订单信息失败，未找到对应的订单信息");
            }
            OrderExtVo order = JsonUtils.parseObject(ordResponse.getResult(), OrderExtVo.class);
            order.setPaymentDealId(transactionId);
            order.setIsInsurance((short) 0);
            order.setPayMode((short) 11);
            order.setPayAppId(appId);
            order.setOpenId(openId);
            order.setPayStatus((short)3);
            order.setOrderStatus((short)3);
            order.setIsPayHandled(1);//支付是否通知并处理0：否，1：是
            logger.info("病案复印微信支付回调, 订单号" + orderNo + ", 调base模块, 更新订单信息入参request=" + JSONObject.toJSONString(order));
            BaseService.callUnderlineFromInternal("yyt.base.order.update", JsonUtils.toJsonString(order));
            logger.info("病案复印微信支付回调, 订单号" + orderNo + "更新成功");
            
        } catch (Exception e) {
            logger.error("onMessage error.", e);
        }

        logger.info("onMessage end.");
    }

}
